//
//  MHTiXianTableViewViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/7/26.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHTiXianTableViewViewController.h"
#import "MHTiXianWeChatTableViewCell.h"
#import "MHTxTableViewCell.h"
#import "MHMoneyTableViewCell.h"
#import "MHTiXianViewModel.h"
#import "MHTiXianFooterView.h"
#import "MHIdentityViewModel.h"
#import "MHTiXianSuccessView.h"

@interface MHTiXianTableViewViewController ()
@property(nonatomic, strong) MHTiXianViewModel *viewModel;
@property(nonatomic, strong) MHTxTableViewCell *tiXian;
@end

@implementation MHTiXianTableViewViewController
@dynamic viewModel;
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.tableView ]
    [self.tableView mh_registerNibCell:MHTxTableViewCell.class];
     [self.tableView mh_registerNibCell:MHMoneyTableViewCell.class];
     [self.tableView mh_registerNibCell:MHTiXianWeChatTableViewCell.class];
    
    @weakify(self);
    [[MHNotificationCenter rac_addObserverForName:MHTiXianSuccessNotification object:nil] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        MHHTTPResponse *response = (MHHTTPResponse *)note.object;
        [self showWithOrderNum: [(NSDictionary *)response.parsedResult objectForKey:@"orderNo"]];
//        [self showWithOrderNum:[(NSDictionary *)note.object objectForKey:@"orderNo"]];
    }];
//    @weakify(self);
    
    // Do any additional setup after loading the view from its nib.
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return  100;
    }else if (indexPath.section == 1)
    {
        return  145;
    }else
    {
       return  60;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
      return 10;
   
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 120;
    }else
    {
        return 0.1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 1) {
        MHTxTableViewCell* txCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MHTxTableViewCell.class)];
        @weakify(self);
       
        self.tiXian = txCell;
        txCell.tixianTextField.bk_shouldReturnBlock = ^(UITextField *field){
            @strongify(self);
            [txCell.tixianTextField resignFirstResponder];
            return YES;
        };
        [txCell.tixianTextField.rac_textSignal subscribeNext:^(NSString *str){
//            NSLog(@"%@",x);//这里的X就是文本框的文字
            if (str.length) {
                txCell.tipLabel.text = self.viewModel.info.txMgs;
            }else
            {
                txCell.tipLabel.text = [NSString stringWithFormat:@"每次提现不低于%@元，每日提现最高总额%@元",FormatFloatToString(self.viewModel.info.minTxMoney),FormatFloatToString(self.viewModel.info.maxTxMoney)];
            }
        }];
        txCell.tixianTextField.delegate = self;
        return  txCell;
    }else if (indexPath.section == 0)
    {
        MHMoneyTableViewCell* moneyCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MHMoneyTableViewCell.class)];
        @weakify(self);
        [RACObserve(self.viewModel.info, settledMoney) subscribeNext:^(MHCarhOprtInfo *info) {
            @strongify(self);
            moneyCell.settledMoneyAmountLabel.text = [NSString stringWithFormat:@"%.2f",self.viewModel.info.settledMoney];
           
        }];
        
        [RACObserve(self.viewModel.info, canTxMoney) subscribeNext:^(MHCarhOprtInfo *info) {
            @strongify(self);
            moneyCell.canTxAmountLabel.text = [NSString stringWithFormat:@"%.2f",self.viewModel.info.canTxMoney];
            
        }];
        
        
        return  moneyCell;
    }else if (indexPath.section == 2)
    {
        MHTiXianWeChatTableViewCell* weChatCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MHTiXianWeChatTableViewCell.class)];
       
        
        return  weChatCell;
    }
    return nil;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return @" ";
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
    //新输入的
    if (string.length == 0) {
        return YES;
    }
    
    //第一个参数，被替换字符串的range
    //第二个参数，即将键入或者粘贴的string
    //返回的是改变过后的新str，即textfield的新的文本内容
    NSString *checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    //正则表达式（只支持两位小数）
    NSString *regex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";
    //判断新的文本内容是否符合要求
    return [self isValid:checkStr withRegex:regex];
    
}

//检测改变过的文本是否匹配正则表达式，如果匹配表示可以键入，否则不能键入
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex
{
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2) {
      MHTiXianFooterView *footer =  [MHTiXianFooterView mh_viewFromXib];
        footer.errorLable.text = self.viewModel.info.txAccountNoPassInfo;
        footer.errorView.hidden = self.viewModel.info.txAccountNoPassInfo.length <= 0;
        footer.errorimage.hidden = self.viewModel.info.txAccountNoPassInfo.length <= 0;
        @weakify(self);
        [footer.tixianBtn bk_whenTapped:^{
            @strongify(self);
            if ([self.tiXian.tixianTextField.text doubleValue] < self.viewModel.info.minTxMoney ||  [self.tiXian.tixianTextField.text doubleValue] >self.viewModel.info.maxTxMoney) {
                [MBProgressHUD mh_showTips:@"提现金额输入范围有误"];
                return;
            }else
            {
                if (self.viewModel.info.isTxAccountPass) {
                   @weakify(self);
                    [[self.viewModel.services.client addCashDetailWithAmount:[self.tiXian.tixianTextField.text doubleValue]]  subscribeNext:^(MHHTTPResponse *respose) {
                        @strongify(self);
                        
            
                        [self showWithOrderNum: [(NSDictionary *)respose.parsedResult objectForKey:@"orderNo"]];
                    } completed:^{
                        
                    }];
                }else
                {
                    if ([self.tiXian.tixianTextField.text doubleValue] > self.viewModel.info.canTxMoney) {
                        [MBProgressHUD mh_showTips:@"超过最大可提现金额"];
                        return;
                    }
                    MHIdentityViewModel *viewModel = [[MHIdentityViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:@([self.tiXian.tixianTextField.text doubleValue])}];
                    [self.viewModel.services pushViewModel:viewModel animated:YES];
                }
               
            }
        }];
        return footer;
    }
    return nil;
}


-(void) showWithOrderNum:(NSString *)orderNum
{
    self.zh_popupController = [zhPopupController new];
    
    MHTiXianSuccessView *tixianSuccess = [MHTiXianSuccessView mh_viewFromXib];
    @weakify(self);
    [tixianSuccess.comfirmBtn bk_whenTapped:^{
      @strongify(self);
        [self.zh_popupController dismiss];
    }];
    
    tixianSuccess.orderNumber.text = [NSString stringWithFormat:@"交易单号:%@\n到账信息请留意微信提醒",orderNum];
    tixianSuccess.width = self.view.width * 0.8;
    [self.zh_popupController presentContentView:tixianSuccess];
    
    self.viewModel.info.settledMoney += [self.tiXian.tixianTextField.text doubleValue];
    self.viewModel.info.canTxMoney -= [self.tiXian.tixianTextField.text doubleValue];
    
}




@end
